package com.yq.cp.controller.basics;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.cp.config.UserThreadLocal;
import com.yq.cp.entity.basics.EquipmentCategory;
import com.yq.cp.entity.basics.EquipmentManagement;
import com.yq.cp.entity.basics.OrganizationalStructure;
import com.yq.cp.entity.basics.SecureManagement;
import com.yq.cp.entity.basics.model.SiteHeaderToUser;
import com.yq.cp.entity.common.ApiResult;
import com.yq.cp.entity.common.PageVo;
import com.yq.cp.entity.data.NengKongDataDay;
import com.yq.cp.entity.permission.User;
import com.yq.cp.mapper.data.NengKongDataDayMapper;
import com.yq.cp.service.basics.EquipmentCategoryService;
import com.yq.cp.service.basics.EquipmentManagementService;
import com.yq.cp.service.basics.OrganizationalStructureService;
import com.yq.cp.service.data.IndexGfService;
import com.yq.cp.service.permission.UserService;
import com.yq.cp.utils.DateTimeUtil;
import com.yq.cp.utils.MD5Util;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 组织架构 前端控制器
 * </p>
 *
 * @author shenyuqing
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/organizationalStructure")
public class OrganizationalStructureController {
    @Resource
    OrganizationalStructureService organizationalStructureService;
    @Resource
    EquipmentManagementService equipmentManagementService;
    @Resource
    EquipmentCategoryService equipmentCategoryService;
    @Resource
    private IndexGfService indexGfService;
    @Resource
    private NengKongDataDayMapper dataDayMapper;
    @Resource
    UserService userService;
    /**
     * 站点管理列表
     * @param vo
     * @return
     */
    @PostMapping("list")
    public ApiResult list(@RequestBody PageVo vo){
        User user = UserThreadLocal.get();
        Page<OrganizationalStructure> page = new Page<>(vo.getPage(), vo.getSize());
        QueryWrapper<OrganizationalStructure> wrapper = new QueryWrapper<>();
        if (!Objects.isNull(vo.getLike())&&!"".equals(vo.getLike()))
            wrapper.eq("name",vo.getLike());
        wrapper.eq("examine",1);
        if (!Objects.isNull(user.getStructureId())){
            OrganizationalStructure byId = organizationalStructureService.getById(user.getStructureId());
            if (!Objects.isNull(byId)){
                if (byId.getType()==1)
                    wrapper.eq("channel_id",byId.getId());
                if (byId.getType()==2)
                    wrapper.eq("region_id",byId.getId());
                if (byId.getType()==3)
                    wrapper.eq("sheng_id",byId.getId());
                if (byId.getType()==4)
                    wrapper.eq("shi_id",byId.getId());
                if (byId.getType()==5)
                    wrapper.eq("qu_id",byId.getId());
                if (byId.getType()==6)
                    wrapper.eq("id",byId.getId());
            }
        }
        if (Objects.isNull(user.getStructureId())&&!Objects.isNull(user.getSiteId())){
            OrganizationalStructure byId = organizationalStructureService.getById(user.getSiteId());
            if (!Objects.isNull(byId))
                wrapper.eq("id",byId.getId());
        }
        wrapper.eq("type",6);
        wrapper.isNull("delete_examine");
        wrapper.orderByDesc("create_time");
        page = organizationalStructureService.page(page,wrapper);
        for (int i = 0; i < page.getRecords().size(); i++) {
            OrganizationalStructure byId = organizationalStructureService.getById(page.getRecords().get(i).getChannelId());
            page.getRecords().get(i).setChannelName(byId.getName());
            OrganizationalStructure byId1 = organizationalStructureService.getById(page.getRecords().get(i).getRegionId());
            page.getRecords().get(i).setRegionName(byId1.getName());
            OrganizationalStructure byId2 = organizationalStructureService.getById(page.getRecords().get(i).getShengId());
            page.getRecords().get(i).setShengName(byId2.getName());
            OrganizationalStructure byId3 = organizationalStructureService.getById(page.getRecords().get(i).getShiId());
            page.getRecords().get(i).setShiName(byId3.getName());
            OrganizationalStructure byId4 = organizationalStructureService.getById(page.getRecords().get(i).getQuId());
            page.getRecords().get(i).setQuName(byId4.getName());
            page.getRecords().get(i).setBelongingRegion(byId2.getName()+byId3.getName()+byId4.getName());
            NengKongDataDay n=new NengKongDataDay();
            n.setId(page.getRecords().get(i).getId());
            n.setTime(DateTimeUtil.dqsj());
            Map<String, Object> map = indexGfService.nyzQuery4(n);
            page.getRecords().get(i).setDrfdl(map.get("dr"));

            BigDecimal newest=new BigDecimal(0);
//            //当日发电量 109-发电量（每小时）
//            BigDecimal newest=new BigDecimal(0);
//            n.setType(115);
//            n.setClassifyNumber(2);
//            newest = dataDayMapper.newest(n);
//            newest=newest==null?new BigDecimal(0):newest.setScale(2, BigDecimal.ROUND_HALF_UP);
//            BigDecimal qxzxz = dataDayMapper.qxzxz3(null,115, n.getYear());
//            qxzxz=qxzxz==null?new BigDecimal(0):qxzxz;
//            newest=newest.subtract(qxzxz);
//            //累计发电量  101-发电量（当日）
//            BigDecimal dr=newest.compareTo(new BigDecimal(0))==-1?new BigDecimal(0):newest;
//            qxzxz = dataDayMapper.qxzxz31(n.getId(), 112,n.getYear(),n.getMonth());
//            qxzxz=qxzxz==null?new BigDecimal(0):qxzxz;
//            BigDecimal qxzdz = dataDayMapper.qxzdz31(n.getId(),112,n.getYear(),n.getMonth());
//            qxzdz=qxzdz==null?new BigDecimal(0):qxzdz;
//            BigDecimal bigDecimal1 = dr.add(qxzdz).subtract(qxzxz).setScale(2, BigDecimal.ROUND_HALF_UP);




//            //当日发电量 109-发电量（每小时）
//            n.setType(115);
//            n.setClassifyNumber(2);
//            newest = dataDayMapper.newest(n);
//            newest=newest==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):newest.setScale(2, BigDecimal.ROUND_HALF_UP);
//            BigDecimal qxzxz = dataDayMapper.qxzxz1(page.getRecords().get(i).getId(),DateTimeUtil.getStrDateTime3(new Date()),115);
//            qxzxz=qxzxz==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):qxzxz;
//            newest=newest.subtract(qxzxz);
//            newest=newest.compareTo(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP))==-1?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):newest;
//            BigDecimal dr=newest;
//            map.put("a109",newest.setScale(2, BigDecimal.ROUND_HALF_UP)+"kWh");
//            page.getRecords().get(i).setDrfdl(newest.setScale(2, BigDecimal.ROUND_HALF_UP));


//            BigDecimal a11=new BigDecimal(0);
//            //发电量
//            n.setType(119);
//            n.setEnergyId(page.getRecords().get(i).getId());
//            n.setClassifyNumber(2);
//            newest = dataDayMapper.newest(n);
//            newest=newest==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):newest.setScale(2, BigDecimal.ROUND_HALF_UP);
//            BigDecimal qxzxz  = dataDayMapper.qxzxz1(n.getEnergyId(),DateTimeUtil.getStrDateTime3(new Date()),119);
//            qxzxz=qxzxz==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):qxzxz;
//            newest=newest.subtract(qxzxz);
//            newest=newest.compareTo(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP))==-1?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):newest;
//            BigDecimal dr=newest;
//            dr=newest;
//            a11=a11.add(dr);

            BigDecimal qxzxz = dataDayMapper.qxzxz1(n.getId(), DateTimeUtil.getStrDateTime3(n.getTime()),119);
            qxzxz=qxzxz==null?new BigDecimal(0):qxzxz;

            BigDecimal qxzdz = dataDayMapper.qxzdz1(n.getId(), DateTimeUtil.getStrDateTime3(n.getTime()),119);
            qxzdz=qxzdz==null?new BigDecimal(0):qxzdz;
            BigDecimal subtract = qxzdz.subtract(qxzxz).setScale(2, BigDecimal.ROUND_HALF_UP);
            map.put("a4",subtract);
            page.getRecords().get(i).setDrfdl(subtract.setScale(2, BigDecimal.ROUND_HALF_UP));

            //累计发电量  101-发电量（当日）
            qxzxz = dataDayMapper.qxzxz31(page.getRecords().get(i).getId(), 119,n.getYear(),n.getMonth());
            qxzxz=qxzxz==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):qxzxz;
            qxzdz = dataDayMapper.qxzdz31(page.getRecords().get(i).getId(),119,n.getYear(),n.getMonth());
            qxzdz=qxzdz==null?new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP):qxzdz;
            BigDecimal bigDecimal1 = qxzdz.subtract(qxzxz).divide(new BigDecimal(1000));

            //a101=a101.add(bigDecimal1);


            page.getRecords().get(i).setLjfdl(bigDecimal1.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return ApiResult.success(page);
    }

    /**
     * 设备信息
     * @param vo
     * @return
     */
    @PostMapping("device")
    public ApiResult device(@RequestBody PageVo vo){
        List<EquipmentCategory> list = equipmentCategoryService.list(new QueryWrapper<EquipmentCategory>()
                .eq("parent_id", 0));
        for (EquipmentCategory equipmentCategory : list) {
            List<EquipmentManagement> equipmentManagements = equipmentManagementService.list(new QueryWrapper<EquipmentManagement>()
                    .eq("site_id", vo.getSiteId())
                    .eq("equipment_category_id",equipmentCategory.getId()));
            equipmentCategory.setEquipmentManagements(equipmentManagements);
        }
        return ApiResult.success(list);
    }

    /**
     * 切换站点
     * @param vo
     * @return
     */
    @PostMapping("switchSite")
    public ApiResult switchSite(@RequestBody PageVo vo){
        Page<OrganizationalStructure> page =organizationalStructureService.switchSite(vo);
        return ApiResult.success(page);
    }

    /**
     *  站点负责人审核列表
     * @return
     */
    @PostMapping("siteHeaderExamineList")
    public ApiResult siteHeaderExamineList(@RequestBody PageVo vo){
        IPage<SiteHeaderToUser> page =  organizationalStructureService.siteHeaderExamineList(vo);
        return ApiResult.success(page);
    }

    /**
     * 切换站点列表-只有站点负责人才有
     * @param
     * @return
     */
    @PostMapping("qhzd")
    public ApiResult qhzd(){
        User user = UserThreadLocal.get();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",user.getPhone());
        wrapper.eq("nickname",user.getNickname());
        //wrapper.isNull("department_id");
        wrapper.isNotNull("site_id");
        List<User> list = userService.list(wrapper);
        if (!list.isEmpty()){
            ArrayList<OrganizationalStructure> structures = new ArrayList<>();
            for (User user1 : list) {
                OrganizationalStructure byId = organizationalStructureService.getById(user1.getSiteId());
                if (!Objects.isNull(byId)&&byId.getType()==6){
                    byId.setUserId(user1.getId());
                    OrganizationalStructure chal = organizationalStructureService.getById(byId.getChannelId());
                    OrganizationalStructure region = organizationalStructureService.getById(byId.getRegionId());
                    OrganizationalStructure sheng = organizationalStructureService.getById(byId.getShengId());
                    OrganizationalStructure shi = organizationalStructureService.getById(byId.getShiId());
                    OrganizationalStructure qu = organizationalStructureService.getById(byId.getQuId());
                    byId.setChannelName(chal.getName());
                    byId.setRegionName(region.getName());
                    byId.setShengName(sheng.getName());
                    byId.setShiName(shi.getName());
                    byId.setQuName(qu.getName());
                    byId.setBelongingRegion(sheng.getName()+shi.getName()+qu.getName());
                    structures.add(byId);
                }

            }
            return ApiResult.success(structures);
        }
        return ApiResult.success();
    }

    @PostMapping("dl")
    public ApiResult dl(@RequestBody User vo){
        User user = userService.cxuser(vo.getId());
        String decoder = MD5Util.decoder(user.getPassword());
        vo.setUsername(user.getUsername());
        vo.setPassword(decoder);
        Map<String, Object> userinfo = userService.login(vo);
        return ApiResult.ok().data(userinfo);
    }


}

